// api/sales.ts
import http from './http'

// 客户相关API

export interface ContactPerson {
  id: number
  name: string
  department: string
  position: string
  phone: string
  email: string
  remark: string
}

export interface Customer {
  id: number
  name: string
  code: string
  contactPersons: string
  status: number
  createdAt: string
  updatedAt: string
}

export interface CustomerQueryParams {
  name?: string
  contactPerson?: string
  phone?: string
  email?: string
  status?: number
  createdAtStart?: string
  createdAtEnd?: string
  page: number
  limit: number
}

export interface CustomerListResponse {
  list: Customer[]
  pagination: {
    page: number
    limit: number
    total: number
  }
  stats: {
    total: number
    active: number
  }
}

// 获取客户列表
export const getCustomers = async (params: CustomerQueryParams): Promise<CustomerListResponse> => {
  const response = await http.get('/customers', { params })
  return response.data
}

// 获取客户详情
export const getCustomerDetail = async (id: number) => {
  const response = await http.get(`/customers/${id}`)
  return response.data
}

// 创建客户
export const createCustomer = async (data: Omit<Customer, 'id' | 'createdAt' | 'updatedAt'>) => {
  const response = await http.post('/customers', data)
  return response.data
}

// 更新客户
export const updateCustomer = async (id: number, data: Partial<Customer>) => {
  const response = await http.put(`/customers/${id}`, data)
  return response.data
}

// 删除客户
export const deleteCustomer = async (id: number) => {
  const response = await http.delete(`/customers/${id}`)
  return response.data
}

// 批量删除客户
export const batchDeleteCustomers = async (ids: number[]) => {
  const response = await http.post('/customers/batch-delete', { ids })
  return response.data
}

// 导出客户
export const exportCustomers = async (params: any) => {
  const response = await http.get('/customers/export', { 
    params,
    responseType: 'blob'
  })
  return response.data
}

// 导出客户模板
export const exportCustomerTemplate = async () => {
  const response = await http.get('/customers/export-template', {
    responseType: 'blob'
  })
  return response.data
}

// 导入客户
export const importCustomers = async (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  const response = await http.post('/customers/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return response.data
}

// 销售订单相关API

export interface SalesOrder {
  id: string
  platformOrderId: string
  platformSource: 'zcy' | 'manual' | 'other'
  customerName: string
  customerCode?: string
  contactPerson?: string
  amount: number
  orderStatus: 'pending' | 'paid' | 'shipped' | 'completed' | 'cancelled'
  invoiceStatus: 'uninvoiced' | 'invoiced' | 'sent'
  invoiceDate?: string
  orderDate: string
  responsibleSalesman?: string
  hasGift: boolean
  editable: boolean
  createdAt: string
  updatedAt: string
}

export interface SalesOrderQueryParams {
  page: number
  limit: number
  orderStatus?: string
  invoiceStatus?: string
  customerName?: string
  orderDateRange?: string[]
  minAmount?: number
  maxAmount?: number
  platformSource?: string
  responsibleSalesman?: string
  platformOrderId?: string
  includeGifts?: boolean
  sortField?: string
  sortOrder?: 'asc' | 'desc'
}

export interface SalesOrderListResponse {
  list: SalesOrder[]
  pagination: {
    page: number
    limit: number
    total: number
  }
}

// 获取销售订单列表
export const getSalesOrders = async (params: SalesOrderQueryParams): Promise<SalesOrderListResponse> => {
  const response = await http.get('/sales-orders', { params })
  const data = response.data
  
  // 处理数据：将purchaserOrganizationName映射到customerName
  if (data && data.list && Array.isArray(data.list)) {
    data.list = data.list.map((order: any) => {
      // 如果存在purchaserOrganizationName但不存在customerName，则设置customerName
      if (order.purchaserOrganizationName && !order.customerName) {
        return {
          ...order,
          customerName: order.purchaserOrganizationName
        }
      }
      return order
    })
  }
  
  return { data }
}

// 获取销售订单详情
export const getSalesOrderDetail = async (id: number) => {
  const response = await http.get(`/sales-orders/${id}`)
  const order = response.data
  
  // 处理数据：将purchaserOrganizationName映射到customerName
  if (order && order.purchaserOrganizationName && !order.customerName) {
    return {
      ...order,
      customerName: order.purchaserOrganizationName
    }
  }
  
  return order
}

// 创建销售订单
export const createSalesOrder = async (data: Omit<SalesOrder, 'id' | 'createdAt' | 'updatedAt'>) => {
  const response = await http.post('/sales-orders', data)
  return response.data
}

// 更新销售订单
export const updateSalesOrder = async (id: number, data: Partial<SalesOrder>) => {
  const response = await http.put(`/sales-orders/${id}`, data)
  return response.data
}

// 删除销售订单
export const deleteSalesOrder = async (id: number) => {
  const response = await http.delete(`/sales-orders/${id}`)
  return response.data
}

// 导入销售订单
export const importSalesOrders = async (file: File, fieldMapping: Record<string, string>) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('fieldMapping', JSON.stringify(fieldMapping))
  
  const response = await http.post('/sales-orders/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return response.data
}

// 导出销售订单模板
export const exportSalesOrderTemplate = async () => {
  const response = await http.get('/sales-orders/export-template', {
    responseType: 'blob'
  })
  return response.data
}

// 销售订单统计信息
export interface SalesOrderStats {
  totalOrders: number
  pendingOrders: number
  completedOrders: number
  problemOrders: number
  monthlyAmount: number
  avgOrderAmount: number
  completionRate: number
  uninvoicedOrders: number
  amountTrend: number
  avgTrend: number
  completionTrend: number
  invoiceTrend: number
}

// 获取销售订单统计信息
export const getSalesOrderStats = async (): Promise<SalesOrderStats> => {
  const response = await http.get('/sales-orders/stats')
  return response.data
}